var Data = require("../../utils/data.js");
const Util = require('../../utils/util.js');
Page({
  data: {
    startIdx:'',
    endIdx:'',
    is_check:false,
    next_check:false
  },
  //==================加载数据================
  onLoad: function (options) {
    if (options.startDate && options.endDate) {
      // var startDate = Data.formatDate(options.startDate,"yyyy-MM-dd");
      //var endDate =  Data.formatDate(options.endDate,"yyyy-MM-dd");
      this.data.startDate = options.startDate;
      this.data.endDate = options.endDate;
    }
    if (options.goods_id) {
      this.data.goods_id = options.goods_id;
    }
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function (res) {
        that.setData({
          token: res.data
        })
      }
    });
    var date = new Date();
    //获取当前的年月
    var cur_year = date.getFullYear();
    var cur_month = date.getMonth() + 1;
    var cur_day = date.getDate();
    // console.log(cur_year);
    // console.log(cur_month);
    // console.log(cur_day);
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    //设置数据
    this.setData({
      org_year: date.getFullYear(),//现在时间的年月日
      org_month: date.getMonth(),
      org_day: cur_day,
      weeks_ch
    })
    this.initData(cur_year, cur_month);
  },
  //初始化数据
  initData: function (cur_year, cur_month) {
    // 计算最近三个月的对象
    var that = this;
    if(that.data.goods_id){
      Util.getGoodsDate({
        year: cur_year,
        month: cur_month,
        goods_id: this.data.goods_id
      }, function (re) {
        that.setData({
          allDays: [
            that.calculateDays(cur_year, cur_month, re.data),
            that.calculateDays(re.next.year, re.next.month, re.next.data),
            that.calculateDays(re.second.year, re.second.month, re.second.data)
          ]
        });
      });
    }else{
      var mObject0 = this.calculateDays(cur_year, cur_month);
      if (cur_month + 1 > 12) {
        cur_year = cur_year + 1;
        cur_month = 1;
      } else {
        cur_month = cur_month + 1;
      }
      var mObject1 = this.calculateDays(cur_year, cur_month);
      if (cur_month + 1 > 12) {//月不能大于12
        cur_year = cur_year + 1;
        cur_month = 1;
      } else {
        cur_month = cur_month + 1;
      }
      var mObject2 = this.calculateDays(cur_year, cur_month);
      if (cur_month + 1 > 12) {//月不能大于12
        cur_year = cur_year + 1;
        cur_month = 1;
      } else {
        cur_month = cur_month + 1;
      }
      var mObject3 = this.calculateDays(cur_year, cur_month);
      if (cur_month + 1 > 12) {//月不能大于12
        cur_year = cur_year + 1;
        cur_month = 1;
      } else {
        cur_month = cur_month + 1;
      }
      var mObject4 = this.calculateDays(cur_year, cur_month);
      this.setData({
        allDays: [mObject0, mObject1, mObject2, mObject3, mObject4]
      });
    }
  },
  // =============获取当月有多少天（下个月月初是多少）==========
  getThisMonthDays: function (year, month) {
    return new Date(year, month, 0).getDate();
  },
  // =============获取当月第一周第一天是周几===========
  getFirstDayOfWeek: function (year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  //====================计算当前年月空的几天 =============
  calculateEmptyGrids: function (year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
    }
    return empytGrids;
  },
  // =====================计算当前年月有哪些天===========
  /**
   * 根据年月计算当前月的天对象状态返回对象
   * mObject 年月对象
   * year  年
   * month 月
   * hasEmptyGrid  是都有空调
   * empytGrids  空天数字
   * days 所有日对象【】
   */
  calculateDays: function (year, month, goods) {
    var that = this;
    var mObject = {};//月对象
    mObject["year"] = year;
    mObject["month"] = month;
    //计算当前年月空的几天
    var empytGrids = this.calculateEmptyGrids(year, month);
    if (empytGrids.length > 0) {
      mObject["hasEmptyGrid"] = true;
      mObject["empytGrids"] = empytGrids;
    } else {
      mObject["hasEmptyGrid"] = false;
      mObject["empytGrids"] = [];
    }
    var days = [];
    var thisMonthDays = this.getThisMonthDays(year, month);//这个月有多少天
    //现在的时间
    var cusDate = new Date(this.data.org_year, this.data.org_month, this.data.org_day);
    var startDate;
    var endDate;
    if (this.data.startDate && this.data.endDate) {
      startDate = Data.stringToDate(this.data.startDate);
      endDate = Data.stringToDate(this.data.endDate);
    }
    if (this.data.startDate) {
      startDate = Data.stringToDate(this.data.startDate);
    }
    var startIdx = this.data.startIdx;
    var endIdx = this.data.endIdx;
    for (let i = 1; i <= thisMonthDays; i++) {
      var day = {};
      var date = new Date(year, month - 1, i);
      day["month"] = month;
      day["now"] = year + '-' + month + '-' + i;
      day["day"] = i;
      var time = parseInt(Data.calculateTime(date, cusDate));
      if (time < 0) {
        day["status"] = 0;
      } else if (time == 0) {
        day["status"] = 1;
      } else {
        day["status"] = 2;
      }
     // console.info(this.data.startDate);
      if (this.data.startDate && this.data.endDate) {
        var stime = parseInt(Data.calculateTime(date, startDate));        
        var etime = parseInt(Data.calculateTime(date, endDate));
        if (stime >= 0 && etime <= 0) {
          day["status"] = 3;
        }
        //console.info(day["status"]);
      } else if (this.data.startDate) {
        var stime = parseInt(Data.calculateTime(date, startDate));
        if (stime == 0) {
          day["status"] = 3;
        }
      }
      if(this.data.goods_id){
        if(goods[i-1].status==1){
          day["status"] = 0;
        }else if (goods[i - 1].price<0.01) {
          day["status"] = 0;
        }
        day["price"] = goods[i-1].price;
        if (!endIdx){
          if (that.data.startMonth == month){
            if (startIdx < i && goods[i - 1].status == 1){
              that.data.is_check = true;
            }
            if (that.data.is_check) {
              day["status"] = 0;
            }
          } else if (that.data.startNow < day["now"]){
            if (goods[i - 1].status == 1){
              that.data.next_check = true;
            }
            if (that.data.is_check || that.data.next_check) {
              day["status"] = 0;
            }
          }
        }
      }
      days.push(day);
    }
    console.info(days);
    mObject["days"] = days;
    return mObject;
  },
  // 选择时间
  selectAction: function (e) {
    //console.log(e.currentTarget.dataset.object);
    //console.info(e);
    var year = e.currentTarget.dataset.object.year;
    var month = e.currentTarget.dataset.object.month;
    var price = e.currentTarget.dataset.price;
    var day = e.currentTarget.dataset.idx + 1;
    var selectDate = new Date(year, month - 1, day);
    //现在的时间
    var cusDate = new Date(this.data.org_year, this.data.org_month, this.data.org_day);
    var time = parseInt(Data.calculateTime(selectDate, cusDate));
    if (time < 0) {
      console.log("请选择合理的时间");
      wx.showToast({
        title: '请选择合理的时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (!price && this.data.goods_id) {
      wx.showToast({
        title: '请选择合理的时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if (this.data.startDate && this.data.endDate) {
      this.data.startDate = Data.formatDate(selectDate, "yyyy-MM-dd");
      this.data.endDate = null;
      this.data.startD = Data.formatDate(selectDate, "MM月dd日");
      this.data.startIdx = e.currentTarget.dataset.idx;
      this.data.endIdx = '';
      this.data.is_check = false;
      this.data.next_check = false;
      this.data.startMonth = e.currentTarget.dataset.month;
      this.data.startNow = e.currentTarget.dataset.now;
    } else if (this.data.startDate) {      
      var endDate = Data.formatDate(selectDate, "yyyy-MM-dd");
      if (endDate == this.data.startDate){
        wx.showToast({
          title: '请选择合理的时间',
          icon: 'none',
          duration: 2000
        })
        return;
      } else if (this.data.startDate>endDate){
        this.data.startIdx = e.currentTarget.dataset.idx;
        console.info(e.currentTarget.dataset.month);
        this.data.startMonth = e.currentTarget.dataset.month;
        this.data.startNow = e.currentTarget.dataset.now;
        this.data.startDate = Data.formatDate(selectDate, "yyyy-MM-dd");
        this.data.startD = Data.formatDate(selectDate, "MM月dd日");
        this.data.is_check = false;
        this.data.next_check = false;
      }else{
        this.data.endIdx = true;
        this.data.endMonth = e.currentTarget.dataset.month;
        this.data.endDate = endDate;
        this.data.endD = Data.formatDate(selectDate, "MM月dd日");
      }
    } else {
      this.data.startIdx = e.currentTarget.dataset.idx;
      this.data.startMonth = e.currentTarget.dataset.month;
      this.data.startNow = e.currentTarget.dataset.now;
      this.data.startDate = Data.formatDate(selectDate, "yyyy-MM-dd");
      this.data.startD = Data.formatDate(selectDate, "MM月dd日");
    }
    this.initData(this.data.org_year, this.data.org_month + 1);
    //返回选择的时间（有起止时间的时候返回）
    if (this.data.startDate && this.data.endDate) {
      // console.log(this.data.startDate);
      //console.log(this.data);
      var sDate = this.data.startDate;
      var eDate = this.data.endDate;
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2]; //上一个页面
      //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
      prevPage.setData({
        date: sDate,
        tomorrow: eDate,
        startD: this.data.startD,
        endD: this.data.endD,
        countD: this.datedifference(sDate, eDate),
        startName: this.checkDay(sDate),
        endName: this.checkDay(eDate)
      })
      console.info(this.data.token);
      Util.getOrderPrice({
        token: this.data.token,
        goods_id: this.data.goods_id,
        start_date: sDate,
        end_date: eDate
      }, function (re) {
        if(re.code==200){
          prevPage.setData({
            order_price: re.data
          })
        }
      })
    }
  },
  checkDay: function (str) {
    var date = Data.formatDate(new Date(), "yyyy-MM-dd");
    if (date == str) {
      return '今天';
    }
    var tomorrow1 = new Date();
    tomorrow1.setDate((new Date()).getDate() + 1);
    var tomorrow = Data.formatDate(new Date(tomorrow1), "yyyy-MM-dd");
    if (tomorrow == str) {
      return '明天';
    }
    var weekDay = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var myDate = new Date(Date.parse(str));
    return weekDay[myDate.getDay()];
  },
  datedifference: function (sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式  
    var dateSpan,
      tempDate,
      iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    dateSpan = Math.abs(dateSpan);
    iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays
  },
  closeCalender: function () {
    var that = this;
    if (this.data.startDate && this.data.endDate) {
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.showToast({
        title: '请选择日期',
        icon: 'none',
        duration: 2000
      })
    }
  }

});